//
//  ContentView.swift
//  SSNote
//
//  Created by shen on 2023/10/17.
//

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(sortDescriptors: [SortDescriptor(\.title, order: .forward)])
    private var notes: FetchedResults<Note>

    var body: some View {
        NavigationStack {
            List {
                ForEach(notes) { note in
                    NavigationLink(value: note) {
                        NoteCell(note: note)
                    }
                }
            }
            .navigationDestination(for: Note.self) { note in
                ComposeNoteView(note: note)
            }
            .navigationTitle("Notes")
            .toolbar {
//                NavigationLink {
//                    ComposeNoteView()
//                } label: {
//                    Label("", systemImage: "square.and.pencil")
//                        .padding()
//                }
            }
        }
    }
}

struct NoteCell: View {
    @State var note: Note

    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter
    }()

    var body: some View {
        VStack {
            Text(note.title!)
                .font(.headline)

            Text(note.body!)
                .font(.subheadline)
                .lineLimit(3)

            Text(dateFormatter.string(from: note.created!))
                .font(.footnote)
                .foregroundStyle(.secondary)
        }
        .padding(8)
    }
}

#Preview {
    ContentView()
        .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
